﻿Public Class iHelperMonkey
    Private QueueLocks As New List(Of String)
    Private Sources As iWatchSources
    Private RegenerateSourcesMenu As Boolean = False
    Private RegenerateWatchers As Boolean = False




    Private Sub iWatch_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.Sources = Sources
    End Sub

    Private Sub iWatch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If My.Settings.Sources Is Nothing Then
            My.Settings.Sources = New iWatchSources
        End If
        ParallelThreads.Value = My.Settings.ParallelThreads
        Sources = My.Settings.Sources
        If Sources.Sources.Count <> 0 Then
            Me.WindowState = FormWindowState.Minimized
        End If
        Me.ShowInTaskbar = False
        Sources.RestartWatchers()
        RegenerateSourcesMenu = True
        RegenerateWatchers = True

    End Sub

    Private Sub AddSourceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddSourceToolStripMenuItem.Click

        Dim WS As iWatchSource
        Try
            WS = New iWatchSource(False)
        Catch ex As Exception
            Exit Sub
        End Try

        Sources.Add(WS)
    End Sub


    Private Sub SourcesToolStripMenuItem_DropDownClosed(ByVal sender As Object, ByVal e As System.EventArgs) Handles SourcesToolStripMenuItem.DropDownClosed
        RegenerateSourcesMenu = True
    End Sub




    Private Sub SourcesToolStripMenuItem_DropDownOpening(ByVal sender As Object, ByVal e As System.EventArgs) Handles SourcesToolStripMenuItem.DropDownOpening
        If RegenerateSourcesMenu Then
            For i = 3 To SourcesToolStripMenuItem.DropDownItems.Count
                SourcesToolStripMenuItem.DropDownItems.RemoveAt(2)
            Next

            Sources.PurgeSourcesMarkedForDeletion()

            Dim DeleteMenuBar As New ToolStripMenuItem
            Dim EditMenuBar As New ToolStripMenuItem
            DeleteMenuBar.Text = "Delete Source"
            EditMenuBar.Text = "Edit Source"
            For Each WS In Sources.Sources
                DeleteMenuBar.DropDownItems.Add(WS.WatchSourceName, Nothing, AddressOf WS.MarkForDeletion)
                EditMenuBar.DropDownItems.Add(WS.WatchSourceName, Nothing, AddressOf WS.EditProperties)
            Next

            SourcesToolStripMenuItem.DropDownItems.Add(DeleteMenuBar)
            SourcesToolStripMenuItem.DropDownItems.Add(EditMenuBar)
            RegenerateSourcesMenu = False
        End If

    End Sub

    Private Sub QuitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuitToolStripMenuItem.Click, QuitToolStripMenuItem1.Click
        My.Settings.Sources = Sources
        Me.Close()
    End Sub

    Private Sub TrayIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TrayIcon.MouseDoubleClick

        If Me.ShowInTaskbar Then
            Me.WindowState = FormWindowState.Minimized
            Me.Visible = False
            Me.ShowInTaskbar = False
        Else
            Me.Visible = True
            Me.ShowInTaskbar = True
            Me.WindowState = FormWindowState.Normal
        End If
    End Sub

    Private Sub QueueTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QueueTimer.Tick


        If ParallelThreads.Value > QueueLocks.Count And Sources.Sources.Count > 0 And QueueProcessingEnabled.Checked Then
            Dim t As System.Threading.Thread
            t = New System.Threading.Thread(AddressOf Me.ProcessFile)
            t.Start()

        End If
    End Sub


    Private Sub ProcessFile()

        'Grab Random File From Random Queue and Set Lock
        Dim RNG As New System.Random
        Dim OriginalFilePath As String
        Dim SN As Integer = RNG.Next(0, Sources.Sources.Count() - 1)

        If Sources.Sources(SN).FileQueue.Count > 0 Then
            OriginalFilePath = Sources.Sources(SN).FileQueue(RNG.Next(0, Sources.Sources(SN).FileQueue.Count - 1))
            QueueLocks.Add(OriginalFilePath)
        Else
            Exit Sub
        End If

        Try
            Dim Input As System.IO.FileStream = IO.File.Open(OriginalFilePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
            Input.Close()
            Dim FileName As String = OriginalFilePath.Substring(OriginalFilePath.LastIndexOf("\"))
            Dim NewFilePath As String
            NewFilePath = OriginalFilePath

            If Sources.Sources(SN).FFMPEGEnabled Then
                'Assign the exepath and directories.
                Dim proc As New System.Diagnostics.Process()
                proc.StartInfo.FileName = "ffmpeg.exe"
                ''Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
                proc.StartInfo.Arguments = "-i """ + NewFilePath + """ " + Sources.Sources(SN).FFMPEGOptions + " """ + Sources.Sources(SN).FFMPEGTempFolder + "\" + FileName + Sources.Sources(SN).FFMPEGNewExtension + """ "
                proc.StartInfo.UseShellExecute = False
                proc.StartInfo.CreateNoWindow = True

                'proc.PriorityClass = ProcessPriorityClass.Idle
                proc.StartInfo.RedirectStandardOutput = False

                proc.Start()
                While Not proc.HasExited
                    Threading.Thread.Sleep(1000)
                End While

                NewFilePath = Sources.Sources(SN).FFMPEGTempFolder + "\" + FileName + Sources.Sources(SN).FFMPEGNewExtension

            End If


            If Sources.Sources(SN).DestinationEnabled Then
                IO.File.Move(OriginalFilePath, Sources.Sources(SN).DestinationPath + "\\" + FileName)
                NewFilePath = Sources.Sources(SN).DestinationPath + "\\" + FileName
            End If



            If Sources.Sources(SN).iTunesEnabled Then



                Dim iTunes As New iTunesLib.iTunesApp
                Dim iTunesStatus = iTunes.LibraryPlaylist.AddFile(NewFilePath)



                While iTunesStatus.InProgress
                    Threading.Thread.Sleep(1000)
                End While


                If Sources.Sources(SN).iTunesTypeCast Then
                End If


                If Sources.Sources(SN).iTunesDeleteAfterCopy Then
                    Try
                        IO.File.Delete(NewFilePath)
                        IO.File.Delete(OriginalFilePath)
                    Catch ex As Exception

                    End Try

                End If
            End If


            'Remove From Queue
            Sources.Sources(SN).FileQueue.Remove(OriginalFilePath)
        Catch ex As Exception
            If ex.Message.StartsWith("Could not find a part of the path") Or ex.Message.StartsWith("Could not find file") Then
                Sources.Sources(SN).FileQueue.Remove(OriginalFilePath)

            End If
        End Try

        QueueLocks.Remove(OriginalFilePath)
    End Sub



    Private Sub GUITimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GUITimer.Tick
        Dim QueueLength As Integer = 0
        For Each Source In Sources.Sources
            QueueLength += Source.FileQueue.Count
        Next
        Text = "iHelperMonkey ( " + QueueLength.ToString + " )"

    End Sub
End Class
